package cn.tedu.charging.device.service;

import cn.tedu.charging.common.pojo.po.ChargingGunInfoPO;
import cn.tedu.charging.common.pojo.po.ChargingStationPO;
import cn.tedu.charging.common.pojo.query.NearStationsQuery;
import cn.tedu.charging.common.pojo.vo.GunInfoVO;
import cn.tedu.charging.common.pojo.vo.StationDetailVO;
import cn.tedu.charging.common.pojo.vo.StationInfoVO;
import cn.tedu.charging.device.repository.GunRepository;
import cn.tedu.charging.device.repository.StationRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private StationRepository stationRepository;
    @Autowired
    private GunRepository gunRepository;

    @Override
    public List<StationInfoVO> getNearStations(NearStationsQuery query) {
        // 业务层 只调用仓储层 做数据读写，仓储成根据需求调用mapper或redis客户端
        return stationRepository.getNearStations(query);
    }

    @Override
    public StationDetailVO getStationDetail(Integer stationId) {
        StationDetailVO vo = new StationDetailVO();
        // 1. 利用stationId 读取站场详情，po.stationName po.address
        ChargingStationPO station = stationRepository.getById(stationId);
        vo.setStationName(station.getStationName());
        vo.setAddress(station.getAddress());
        // 2. gunPOList 需要gunMapper gunRepository支持
        // 2.1 单表查询 pileMapper list<Pile> 循环gunMapper List<Gun>
        // 2.2 自定义查询需求，执行关联查询
        // 2.3 设计枪的缓存数据，利用站场id绑定多个枪缓存对象 List数据类型
        List<ChargingGunInfoPO> guns = gunRepository.getGunsByStationId(stationId);
        log.debug("查询到关联的枪:{}", guns);
        //读取站场关联的枪的list 转化成GunInfoVO列表给返回值vo使用
        if (guns != null && guns.size() > 0) {
            List<GunInfoVO> gunVos = new ArrayList<>();
            for (ChargingGunInfoPO gun : guns) {
                GunInfoVO gunInfoVO = new GunInfoVO();
                BeanUtils.copyProperties(gun, gunInfoVO);
                gunVos.add(gunInfoVO);
            }
            vo.setGunInfoPOList(gunVos);
        }
        // 读取站场关联的枪的list 转化成GunInfoVO列表返回给vo使用
        return vo;
    }
}
